package com.zwz.crawler.basic;

import com.zwz.constant.Constant;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import javax.crypto.Mac;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import static com.zwz.constant.Constant.ENTERPRISE_ID;

@Slf4j
public class TungeeStockHolderQuery {
    public static void startTungeeStockHolderQuery() {
        // 请求参数配置
//        final String enterpriseId = "577de19eadf21dc4";
        final int start = 0;
        final int end = 10;

        // 前置校验
        validateParameters(start, end);

        try {
            // 构建请求URL（严格编码）
            String encodedId = URLEncoder.encode(ENTERPRISE_ID, String.valueOf(StandardCharsets.UTF_8));
            String url = String.format(
                    "https://sales.tungee.com/api/enterprise/detail/stock-holder-page?enterprise_id=%s&start=%d&end=%d",
                    encodedId, start, end
            );

            // 发送请求
            Connection.Response response = Jsoup.connect(url)
                    .method(Connection.Method.GET)
                    // 请求头精确配置
                    .header("authority", "sales.tungee.com")
                    .header("accept", "*/*")
                    .header("accept-encoding", "gzip, deflate, br, zstd")
                    .header("accept-language", "zh-CN,zh;q=0.9")
                    .header("cache-control", "no-cache")
                    .header("cookie", Constant.cookies)
                    .header("pragma", "no-cache")
                    .header("priority", "u=1, i")
                    .header("referer", "https://sales.tungee.com/enterprise-details/577de19eadf21dc4/enterprise-information/basic-information")
                    .header("sec-ch-ua", "\"Not;A=Brand\";v=\"24\", \"Chromium\";v=\"128\"")
                    .header("sec-ch-ua-mobile", "?0")
                    .header("sec-ch-ua-platform", "\"Windows\"")
                    .header("sec-fetch-dest", "empty")
                    .header("sec-fetch-mode", "cors")
                    .header("sec-fetch-site", "same-origin")
                    .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36")
                    .header("x-tonxis-pid", "67864ea75f69e05d3b544ca7")
                    // 连接配置
                    .ignoreContentType(true)
                    .ignoreHttpErrors(true)
                    .maxBodySize(0)
                    .timeout(30000)
                    .execute();

            // 处理响应
            processResponse(response);

        } catch (IOException e) {
            handleNetworkException(e);
        }
    }

    // 参数校验
    private static void validateParameters(int start, int end) {
        if (start < 0 || end <= start) {
            throw new IllegalArgumentException("分页参数无效 start: " + start + ", end: " + end);
        }
        if (end - start > 50) {
            throw new IllegalArgumentException("分页数量超过限制（最大50）");
        }
    }


    public static void main2(String[] args) throws IOException, InterruptedException {

        autoPaginationQuery("577de19eadf21dc4");
    }
    // 响应处理
    private static void processResponse(Connection.Response response) {
       log.info("HTTP状态码: " + response.statusCode());
//       //log.info("响应内容:\n" + response.body());
        switch (response.statusCode()) {
            case 200:
               log.info("股东信息获取成功");
                break;
            case 401:
                System.err.println("[认证过期] 需要：");
                System.err.println("1. 检查Cookie中的accountCenterSessionId有效期");
                System.err.println("2. 确认doncusSessionId是否有效");
                break;
            case 403:
                System.err.println("[权限不足] 可能原因：");
                System.err.println("1. 当前账户无查看股东信息权限");
                System.err.println("2. 企业信息属于敏感数据需要额外授权");
                break;
            case 429:
                System.err.println("[请求频繁] 建议：");
                System.err.println("1. 添加5-10秒请求间隔");
                System.err.println("2. 使用IP代理池轮换");
                break;
            default:
                System.err.println("未知错误: " + response.statusCode());
        }
    }

    // 网络异常处理
    private static void handleNetworkException(IOException e) {
        System.err.println("网络请求失败，原因：");
        if (e.getMessage().contains("Timeout")) {
            System.err.println("1. 连接超时，建议增加超时时间");
        } else if (e.getMessage().contains("Connection refused")) {
            System.err.println("2. 连接被拒绝，检查代理设置");
        } else {
            e.printStackTrace();
        }
    }

    // 动态Cookie刷新示例
//    private static Map<String, String> refreshCookies() throws IOException {
//        return Jsoup.connect("https://user.tungee.com/login")
//                .data("phone", "13800138000")
//                .data("password", "加密后的密码")
//                .post()
////                .cookies();
//    }   需要刷新cookies




    public static void autoPaginationQuery(String enterpriseId) throws IOException, InterruptedException {
        int pageSize = 10;
        for (int start = 0; ; start += pageSize) {
            String url = String.format(
                    "https://sales.tungee.com/api/enterprise/detail/stock-holder-page?enterprise_id=%s&start=%d&end=%d",
                    URLEncoder.encode(enterpriseId, String.valueOf(StandardCharsets.UTF_8)), start, start + pageSize
            );

//            Connection.Response response = Jsoup.connect(url)
//                    // ...其他配置...
//                    .execute();
            Connection.Response response = Jsoup.connect(url)
                    .method(Connection.Method.GET)
                    // 请求头精确配置
                    .header("authority", "sales.tungee.com")
                    .header("accept", "*/*")
                    .header("accept-encoding", "gzip, deflate, br, zstd")
                    .header("accept-language", "zh-CN,zh;q=0.9")
                    .header("cache-control", "no-cache")
                    .header("cookie", "_tx_pid=67864ea75f69e05d3b544ca7; __wpkreporterwid_=cc4a07fc-7bb9-40a4-96bc-2cbac34b658f; ...完整Cookie内容...")
                    .header("pragma", "no-cache")
                    .header("priority", "u=1, i")
                    .header("referer", "https://sales.tungee.com/enterprise-details/577de19eadf21dc4/enterprise-information/basic-information")
                    .header("sec-ch-ua", "\"Not;A=Brand\";v=\"24\", \"Chromium\";v=\"128\"")
                    .header("sec-ch-ua-mobile", "?0")
                    .header("sec-ch-ua-platform", "\"Windows\"")
                    .header("sec-fetch-dest", "empty")
                    .header("sec-fetch-mode", "cors")
                    .header("sec-fetch-site", "same-origin")
                    .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36")
                    .header("x-tonxis-pid", "67864ea75f69e05d3b544ca7")
                    // 连接配置
                    .ignoreContentType(true)
                    .ignoreHttpErrors(true)
                    .maxBodySize(0)
                    .timeout(30000)
                    .execute();



            if (response.statusCode() != 200) break;
            if (response.body().contains("\"empty\":true")) break;


            // 处理响应
            processResponse(response);


            // 处理数据...
            Thread.sleep(5000); // 5秒间隔
        }
    }



//    private static String generateSignature(String enterpriseId, int start, int end) {
//        long timestamp = System.currentTimeMillis();
//        String rawData = String.format("%s|%d|%d|%d", enterpriseId, start, end, timestamp);
//        try {
//            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
//            sha256_HMAC.init(new SecretKeySpec("your_secret_key".getBytes(), "HmacSHA256"));
//            byte[] result = sha256_HMAC.doFinal(rawData.getBytes());
//            return Base64.getEncoder().encodeToString(result);
//        } catch (Exception e) {
//            throw new RuntimeException("签名生成失败", e);
//        }
//    }




}